/**
 * @author porfitron
 * youtube browser
 * Ver. Aug. 7, 2008
 */

//*** Ping the Stat Server *** ///
statFeedNo = 1454;
loadScript("http://myDivXConnected.com/pMaker/includes/statsPush.js");

loadScript("regions.js");
loadScript("swfobject/swfobject.js");

var youtubeXHR;
var count = 1;

var numEntries;

var title;
var thumbnail;
var address;
var videoId;

var reg = "US";

var feeds = new Array("/most_viewed?time=today","/most_recent","/top_rated","/top_favorites","/most_discussed","/most_linked","/most_responded","/recently_featured");
var feedTitles = new Array("Today's Most Viewed","Most Recent","Top Rated","Top Favorites","Most Discussed","Most Linked","Most Responded","Recently Featured")
var feedCount = 0;

var youtubeStorage = "youtubeChromeless";
var youtubeVideoId;

// XML Namespace resolver for XPath namespace resolution
function NSResolver(prefix) 
{
	if(prefix == 'media') 
	{
		return "http://search.yahoo.com/mrss/";
	}
	else if (prefix == 'ns1')
	{
		return "http://www.w3.org/2005/Atom";
	}
	else if (prefix == 'gphoto')
	{
		return "http://schemas.google.com/photos/2007";
	}
	return null;
}

// Takes a definition document and populates the various DCTK controls

function handleYoutubeResult(doc){
	// extract information with XPath
	
	numEntries = doc.evaluate("count(//ns1:entry)", doc, NSResolver, XPathResult.ANY_TYPE, null).numberValue;
	
	var titles = new Array()
	for (var i = 1; i <= numEntries; i++) {
		titles[i] = doc.evaluate("//ns1:entry[" + i + "]/ns1:title", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
	}
	var thumbnails = new Array()
	for (var i = 1; i <= numEntries; i++) {
		thumbnails[i] = doc.evaluate("//ns1:entry[" + i + "]/media:group/media:thumbnail[4]/@url", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
	}
	var vidSrc = new Array()
	for (var i = 1; i <= numEntries; i++) {
		vidSrc[i] = doc.evaluate("//ns1:entry[" + i + "]/media:group/media:content[1]/@url", doc, NSResolver, XPathResult.STRING_TYPE, null).stringValue;
	}
	
	title = titles[count]
	thumbnail = thumbnails[count]
	address = vidSrc[count];
	
	videoId = thumbnail.split("/");
	connected.debug.print(videoId[4]);
	
	var storage = connected.openStorage(youtubeStorage,true)
	storage.set(youtubeVideoId,videoId[4])
	
	//connected.debug.print(numEntries);
	//connected.debug.print(titles[count]);
	connected.debug.print(thumbnails[count]);
	connected.debug.print(feeds[feedCount]);
	connected.debug.print(feedCount);
	//connected.debug.print(vidSrc[count]);

	var dctk = connected.toolkit;
	// populate DCTK controls
    vidTxt = dctk.getElementById("vidTxt");
    vidTxt.text = titles[count];
	vidThumb = dctk.getElementById("vidThumb");
    vidThumb.img.src = thumbnails[count];
	
}

function onYoutubeXHRStateChange()
{
    if (youtubeXHR.readyState == 4)
    {
        if (youtubeXHR.status == 200)
        {
           handleYoutubeResult(youtubeXHR.responseXML);
        }
    }
}

function startYoutubeRequest()
{
    youtubeXHR = new XMLHttpRequest();
    youtubeXHR.onreadystatechange = onYoutubeXHRStateChange;
    youtubeXHR.open("GET", "http://gdata.youtube.com/feeds/api/standardfeeds/"+reg+feeds[feedCount], true);
    youtubeXHR.send(null);
}

function mainButtonHandler(e)
{
	var dctk = connected.toolkit;
	
    switch(e.buttonId)
    {
        case dcKeyEvent.BUTTON_ID_BACK:
        {
            // navigate back
            if (window.history.length)
                window.history.back();
        }
		case dcKeyEvent.BUTTON_ID_RIGHT:
			if (count < numEntries)
            count++;
			onLoadComplete();
        break;
		case dcKeyEvent.BUTTON_ID_LEFT:
			if (count > 1)
            --count;
			onLoadComplete();
        break;
		
		case dcKeyEvent.BUTTON_ID_PAGEUP:
			if (feedCount < 7) {
			feedCount++;
			count = 1;
			onLoadComplete();	
			}
			else if (feedCount == 7) {
			count = 1;
			feedCount = 0;
			onLoadComplete();	
			}
			
        break;
		case dcKeyEvent.BUTTON_ID_PAGEDOWN:
			if (feedCount > 0){
			 --feedCount;
			count = 1;
			onLoadComplete();	
			}
			else if (feedCount == 0) {
			 feedCount = 7;
			count = 1;
			onLoadComplete();	
			}
        break;
		
		case dcKeyEvent.BUTTON_ID_UP:
			if (feedCount < 7) {
			feedCount++;
			count = 1;
			status="";
			onLoadComplete();	
			}
			else if (feedCount == 7) {
			count = 1;
			feedCount = 0;
			onLoadComplete();	
			}
        break;
		case dcKeyEvent.BUTTON_ID_DOWN:
			if (feedCount > 0){
			 --feedCount;
			count = 1;
			onLoadComplete();	
			}
			else if (feedCount == 0) {
			 feedCount = 7;
			onLoadComplete();	
			}
        break;
		
		case dcKeyEvent.BUTTON_ID_SELECT:
 			var dctk = connected.toolkit;
        
			var height = connected.outputHeight;
			var width = connected.outputWidth;

			
			var params = connected.createPageDescriptor();
			params.uri = "chromeless.html";
			params.pageType = dcIConnected.PT_HTML;
			if (width/height >= 16/9) {
                params.viewConstraints.addResolutionConstraint(640, 360); //16:9
	        }
	        else if (width/height <= 4/3) {
	            params.viewConstraints.addResolutionConstraint(480, 360); //4:3
	        }
			params.audioCapture = true;
			params.htmlInputFocusMode = dcIPageDescriptor.FOCUS_MODE_OBJECT;
			// load the page
			var storage = connected.openStorage(youtubeStorage,true);
			printVideoId = storage.get(youtubeVideoId,videoId);
			connected.debug.print(printVideoId);
			connected.loadFromPageDescriptor(params);
			

        break;
		
		case dcKeyEvent.BUTTON_ID_MENU:
		{
			showPopup();
		}
		break;
    }
}

function onLoadComplete(){
	var dctk = connected.toolkit;
	
	dctk.logicalWidth = 100;
	dctk.logicalHeight = 100;
	
	// create root panel
	var root = dctk.createPanelCtrl("root", true);
	root.width = 100;
	root.height = 100;
	root.backgroundStyle = dctkIElement.BACKGROUND_STYLE_IMAGE;
	root.backgroundImg.src  = "screen-01.png";
	root.color.rgb = 0xFFFFFF;
	root.onUnhandledKeyEvent = mainButtonHandler;
	dctk.rootPanel = root;
	
	var vidThumb = dctk.createImageCtrl("vidThumb", true);
	vidThumb.setRect(3, 2, 75, 98);
	vidThumb.img.async = true;
	root.addChild(vidThumb);
	
	var overlayBottom = dctk.createImageCtrl("overlayBottom", true);
	overlayBottom.setRect(0, 3, 78, 21);
	overlayBottom.color.rgba = 0x5B5B5B;
	overlayBottom.img.src = "overlay.png";
	overlayBottom.img.async = true;
	root.addChild(overlayBottom);
	
	var overlayTop = dctk.createImageCtrl("overlayTop", true);
	overlayTop.setRect(0, 80, 75, 110);
	overlayTop.color.rgba = 0x5B5B5B;
	overlayTop.img.src = "overlay.png";
	overlayTop.img.async = true;
	root.addChild(overlayTop);
	
	var vidTxt = dctk.createLabelCtrl("vidTxt", true);
	vidTxt.font = dctk.createFontByFacename("Arial Narrow", true, false);
	vidTxt.setRect(4, 12, 73, 19);
	vidTxt.textColor.rgb = 0xCCCCCC;
	vidTxt.fontSize = 4.5;
	vidTxt.align = dctkLabel.TS_CENTER;
	vidTxt.valign = dctkLabel.TS_MIDDLE;
	root.addChild(vidTxt);
	
	var feedTxt = dctk.createLabelCtrl("feedTxt", true);
    feedTxt.font = dctk.createFontByFacename("Arial Narrow", true, false);
    feedTxt.setRect(4, 85, 73, 95);
    feedTxt.textColor.rgb = 0xCCCCCC;
    feedTxt.fontSize = 7;
    feedTxt.align = dctkLabel.TS_CENTER;
	feedTxt.valign = dctkLabel.TS_MIDDLE;
    feedTxt.text = feedTitles[feedCount];
    root.addChild(feedTxt);
	
	var naTxt = dctk.createLabelCtrl("naTxt", true);
	naTxt.font = dctk.createFontByFacename("Arial Narrow", true, false);
	naTxt.setRect(4, 45, 73, 55);
	naTxt.textColor.rgb = 0xFFFF00;
	naTxt.fontSize = 4.5;
	naTxt.align = dctkLabel.TS_CENTER;
	naTxt.valign = dctkLabel.TS_MIDDLE;
	naTxt.text = status;
	root.addChild(naTxt);
	
	var tvFrame = dctk.createImageCtrl("tvFrame", true);
	tvFrame.left = 0;
	tvFrame.top = 100;
	tvFrame.right = 100;
	tvFrame.bottom = 0;
	tvFrame.img.src= "tv-frame.png";
	tvFrame.img.async = true;
	root.addChild(tvFrame);
	
	var regTxt = dctk.createLabelCtrl("regTxt", true);
	regTxt.font = dctk.createFontByFacename("Arial Narrow", true, false);
	regTxt.setRect(77, 34, 99, 43);
	regTxt.textColor.rgb = 0x9e9e9e;
	regTxt.fontSize = 4;
	regTxt.align = dctkLabel.TS_CENTER;
	regTxt.valign = dctkLabel.TS_MIDDLE;
	regTxt.text = "Made in "+reg+" (menu)";
	root.addChild(regTxt);
	
	var logoTube = dctk.createImageCtrl("logoTube", true);
	logoTube.setRect(76, 82, 86, 97);
	logoTube.color.rgba = 0x3C3C3C;
	logoTube.img.src = "logo-tilt.png";
	root.addChild(logoTube);
	
	var logoConnected = dctk.createImageCtrl("logoConnected", true);
	logoConnected.setRect(77, 1, 98, 31);
	logoConnected.color.rgba = 0x5B5B5B;
	logoConnected.img.src = "logo_connected-solo.png";
	root.addChild(logoConnected);
	
	startYoutubeRequest();
	
	//connected.toolkit.debug.drawElementOutline = true;
	
}
